package com.brillilab.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;

public class CompareUtils {

    /**
     * 字符串首拼音首字母(包含字母开头排序)
     * @param s1
     * @param s2
     * @return
     */
    public static int comparePinYin(String s1,String s2){
        try {
            char p1 = s1.charAt(0);
            char p2 = s2.charAt(0);
            if(p1<='z' && p1<p2){
                return -1;
            }else if(p2<='z' && p2<p1){
                return 1;
            }else if(p1 == p2){
                return 0;
            }else if(p1 > 'z' && p2 > 'z'){
                p1 = getFirstChar(s1);
                p2 = getFirstChar(s2);
                return Integer.compare((int) p1, (int) p2);
            }
            return Integer.compare((int) p1, (int) p2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return 0;
        }
    }
    private static char getFirstChar(String name) throws UnsupportedEncodingException {
        name = name.toLowerCase();
        byte[] bytes1 = name.substring(0, 1).getBytes("utf-8");
        char p1 = ' ';
        if (bytes1.length == 3) {
            p1 = PinyinHelper.toHanyuPinyinStringArray(name.charAt(0))[0].charAt(0);
        } else {
            p1 = name.charAt(0);
        }
        return p1;
    }

    /**
     * 获取指定字符的首字母大写
     * @param name
     * @return
     */
    public static String getNameFirstChar(String name) {
        String firstChar="";
        try{
            if(StringUtils.isNotBlank(name)) {
                char[] charArray = name.toCharArray();
                StringBuilder pinyin = new StringBuilder();
                //判断是否为汉字
                if (charArray[0] > 128) {
                    pinyin.append(PinyinHelper.toHanyuPinyinStringArray(charArray[0])[0], 0, 1);
                    firstChar = pinyin.toString().toUpperCase();
                }else {
                    firstChar=name.substring(0,1).toUpperCase();
                }
            }
        }catch (Exception ex){
            System.out.println("获取首字母失败，字符："+name);
            return "Z";
        }
        return firstChar;
    }
}
